package com.joven.shelltest.utils.encrypt;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * 加密解密算法
 * @author wangqilin
 */
@Repository
public class AesUtil {

    private static final String KEY_ALGORITHM = "AES";
    /**
     * 默认的加密算法
     */
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * getAESRandomKey生成后，使用一个固定key
     */
    private static String key="263858998315569";

    /**
     * 将key放入配置
     */
    @Value("${mybatis.aes.key:123}")
    private String mybatisKey;

    private static String actualKey;

    @PostConstruct
    public void init(){
        actualKey = mybatisKey;
    }

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content) throws Exception {
        if(content==null||content.length()==0){
            return "";
        }
        return  encrypt(content,key);
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @return
     */
    public String decrypt(String content) {

        if(content==null||content.length()==0){
            return "";
        }
        return  decrypt(content,key);
    }
    /**
     * 随机生成密钥
     *
     * @return
     */
    public static String getAESRandomKey() {
        SecureRandom random = new SecureRandom();
        long randomKey = random.nextLong();
        return String.valueOf(randomKey);
    }

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @return 返回Base64转码后的加密数据
     */
    public static String encryptMybatis(String content) {
        if(content==null||content.length()==0){
            return "";
        }
        return  encrypt(content,actualKey);
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @return
     */
    public static String decryptMybatis(String content) {
        if(content==null||content.length()==0){
            return "";
        }
        return  decrypt(content,actualKey);
    }

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @param key     加密密钥
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String key){
            // 创建密码器
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            byte[] byteContent = content.getBytes("utf-8");
            // 初始化为加密模式的密码器
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));
            // 加密
            byte[] result = cipher.doFinal(byteContent);
            //通过Base64转码返回
            return byte2Base64(result);
        } catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @param key
     * @return
     */
    public static String decrypt(String content, String key) {
        try {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
            //执行操作
            byte[] result = cipher.doFinal(base642Byte(content));
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @param key
     * @return
     */
    public static String decrypt2(String content, String key) {
        try {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey2(key));
            //执行操作
            byte[] result = cipher.doFinal(base642Byte(content));
            return new String(result, "utf-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    private static SecretKeySpec getSecretKey2(final String key) {
        SecretKeySpec skey;
        try {
            skey = new SecretKeySpec(key.getBytes("utf-8"), "AES");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return skey;
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String key) {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        try {
            KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            // 此类提供加密的强随机数生成器 (RNG)，该实现在windows上每次生成的key都相同，但是在部分linux或solaris系统上则不同。

            // 指定算法名称，不同的系统上生成的key是相同的。
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key.getBytes());
            //AES 要求密钥长度为 128
            kg.init(128, random);
            //生成一个密钥
            SecretKey secretKey = kg.generateKey();
            // 转换为AES专用密钥
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 字节数组转Base64编码
     *
     * @param bytes
     * @return
     */
    public static String byte2Base64(byte[] bytes) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    /**
     * Base64编码转字节数组
     *
     * @param base64Key
     * @return
     * @throws IOException
     */
    public static byte[] base642Byte(String base64Key) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(base64Key);
    }

    public static void main(String[] args){
        System.out.println(decrypt("Q5H8ej63Y0odTTrsnqTV5PaMvj5k2yZyPUSPIdUdVbOsDAF4LHn8zAdMoiBNeilogMW2LKOQBU+PdnQAIKuHrNeqvyGi3xt9veV2Jon+b0iIDCMVFF91vbtKLWuVJJde/ltGm3wKip+J3zDnzNRORA0Mm4MaVPa9ckPEUcveye+P1Ms4SEY0fKpq9N2p5+NAo2XExZbS51PGRFDopTQqOdLTmZ4EZ7juifD49I3xQYCNBJmWE9p66nQeUmbtTL+v231QLN43C63nrKSB6thNIGwWG7mocFNWTeRiG3N07N65bCD9xaJ7wa1xQoAmZOFa3OPuTCLCgIGXRydRgn7v2hwAojRWkoDLRi7S/ycthLWkkzpTi0qxxlWNLhalsw2gXdxXMOTpMho4oarxVlfGGA==","uVr2iNJr2NevgSN6sED9uA=="));
    }
}
